package org.nbict.iot.protocol.context;

import java.util.Arrays;

/**
 * Created by songseven on 18/6/10.
 */
public class BinaryPacket {
    private byte[] buffer;
    private int size;
    private int start;
    private int end;

    private int range; //当前解析的报文范围，只向后看

    public BinaryPacket(byte[] raw) {
        if (raw != null) {
            this.buffer = raw;
            this.size = raw.length;
            this.start = 0;
            this.end = 0;
            this.range = 0;
        }
    }

    private byte[] slice(int from, int to) {
        if (to < from) {
            //throw exception
        }
        byte[] slice = Arrays.copyOfRange(buffer, from, to);
        //buffer = Arrays.copyOfRange(buffer, to, size); //可以优化，不进行拷贝
        size = size - (to - from);
        return slice;
    }

    /**
     * 像贪吃蛇一样，从原始报文吃进length长度的字节数组，吐出响应长度的字节数组
     * @param length
     * @return
     */
    public byte[] eat(int length) {
        end = start + length;
        byte[] eaten = slice(start, end);
        start = end;
        return eaten;
    }

    public int size() {
        return this.size;
    }

    public int current() {
        return this.start;
    }

    public void rangeReset(int range) { //test
        this.range = start + range;
    }

    public boolean inRange() {
        return (start < range);
    }

    /**
     * 跳过位数
     * @return  context
     */
    public BinaryPacket skip(int len) {
        if (len  > 0) eat(len);
        return this;
    }
}
